
function TreeNode(val, left, right) {
    this.val = (val===undefined ? 0 : val)
    this.left = (left===undefined ? null : left)
    this.right = (right===undefined ? null : right)
}

/**
 * @param {number[]} preorder
 * @return {TreeNode}
 */
var bstFromPreorder = function(preorder) {
  if(preorder.length == 0)
    return null;
  let root = new TreeNode(preorder[0]), index = -1;
  if(preorder.length == 1)
    return root;
  for(let i = 1; i < preorder.length; i++) {
    if(preorder[i] > preorder[0]) {
      index = i;
      break;
    }
  }
  if(index === -1){
    root.left = bstFromPreorder(preorder.slice(1, preorder.length));
    root.right = null;
  }
  else {
    root.left = bstFromPreorder(preorder.slice(1, index));
    root.right = bstFromPreorder(preorder.slice(index, preorder.length));
  }
  return root;
};
let preorder = [8,5,1,7,10,12];
console.log(bstFromPreorder(preorder));
preorder = [1,3];
console.log(bstFromPreorder(preorder));
preorder = [4, 2];
console.log(bstFromPreorder(preorder));
// let preorder = [8,5,1,7,10,12], index = 4;
// console.log(preorder.slice(1, index));
// console.log(preorder.slice(index, preorder.length));
// let arr1 = [5,1,7], index1 = 2, arr2 = [10,12], index2 = 1;
// console.log(arr1.slice(1, index1), arr1.slice(index1, arr1.length));
// console.log(arr2.slice(1, index2), arr2.slice(index2, arr2.length));

